import useStore from '@/stores'
import type { Ref } from 'vue'
import { storeToRefs } from 'pinia'

export class Token {
  isInit: boolean = false
  token: Ref<string> | undefined
  getToken() {
    if (!this.isInit) this.init()
    return this.token?.value
  }
  setToken(newToken: string) {
    if (!this.isInit) this.init()
    if (this.token) this.token.value = newToken
  }
  removeToken() {
    if (!this.isInit) this.init()
    if (this.token) this.token.value = ''
  }

  init() {
    const { user } = useStore()
    const { token } = storeToRefs(user)
    this.token = token
    this.isInit = true
  }
}

/**
 * 检查用户是否有权限
 * @param primission 权限
 * @returns 是否有权限
 */
export const checkPermission = (primission: string | string[]) => {
  const allPermission = '*:*:*'
  const { user } = useStore()
  const { userInfo } = storeToRefs(user)

  return (
    userInfo.value.permissions.includes(allPermission) ||
    userInfo.value.permissions.some(permission => {
      if (Array.isArray(primission)) {
        return primission.includes(permission)
      } else {
        return permission === primission
      }
    })
  )
}

const tokenUtil = new Token()
export { tokenUtil }
